package com.yanggeng.demo.beginnerguidedemo.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.yanggeng.demo.beginnerguidedemo.R;
import com.yanggeng.demo.beginnerguidedemo.activity.customview.BatteryProgressBarActivity;
import com.yanggeng.demo.beginnerguidedemo.activity.customview.LineChartActivity;
import com.yanggeng.demo.beginnerguidedemo.activity.customview.PieChartActivity;
import com.yanggeng.demo.beginnerguidedemo.activity.customview.RadarViewActivity;
import com.yanggeng.demo.beginnerguidedemo.activity.customview.SignActivity;
import com.yanggeng.demo.beginnerguidedemo.activity.customview.TestActivity;
import com.yanggeng.demo.beginnerguidedemo.activity.customview.TextInputLayoutActivity;
import com.yanggeng.demo.beginnerguidedemo.activity.customview.TopologyActivity;
import com.yanggeng.demo.beginnerguidedemo.utils.DeviceParams;
import com.yanggeng.demo.beginnerguidedemo.utils.FileUtils;
import com.yanggeng.demo.beginnerguidedemo.utils.ScannerInterface;
import com.yanggeng.demo.beginnerguidedemo.utils.SendMailUtils;
import com.yanggeng.demo.beginnerguidedemo.utils.SnackbarUtil;
import com.yanggeng.demo.beginnerguidedemo.utils.ToastUtil;
import com.yanggeng.demo.beginnerguidedemo.utils.ValidateUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_FILE = 102;
    private static final String RES_ACTION = "android.intent.action.SCANRESULT";

    private Activity context;
    private View mainView;
//    private HighLight mHighLight;
    private BottomSheetDialog bottomSheetDialog;
    private ScannerInterface scanner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        getUUID();
        initScanner();
//        blurBackground();
        mainView = findViewById(R.id.activity_main);
        findViewById(R.id.btn_alert).setOnClickListener(this);
        findViewById(R.id.btn_confirm).setOnClickListener(this);
        findViewById(R.id.btn_add_photo).setOnClickListener(this);
        findViewById(R.id.btn_center_toast).setOnClickListener(this);
        findViewById(R.id.btn_pie_chart).setOnClickListener(this);
        findViewById(R.id.btn_line_chart).setOnClickListener(this);
        findViewById(R.id.btn_grid_view).setOnClickListener(this);
        findViewById(R.id.btn_tips_test).setOnClickListener(this);
        findViewById(R.id.btn_to_mine).setOnClickListener(this);
        findViewById(R.id.btn_to_main).setOnClickListener(this);
        findViewById(R.id.btn_bottom_sheet_dialog).setOnClickListener(this);
        findViewById(R.id.btn_editview).setOnClickListener(this);
        findViewById(R.id.btn_kotlin).setOnClickListener(this);
        findViewById(R.id.btn_tablayout).setOnClickListener(this);
        findViewById(R.id.btn_send_mail).setOnClickListener(this);
        findViewById(R.id.btn_share).setOnClickListener(this);
        findViewById(R.id.btn_db).setOnClickListener(this);
        findViewById(R.id.btn_test).setOnClickListener(this);
        findViewById(R.id.btn_fab).setOnClickListener(this);
        findViewById(R.id.btn_qr).setOnClickListener(this);
        findViewById(R.id.btn_map).setOnClickListener(this);
        findViewById(R.id.btn_weather).setOnClickListener(this);
        findViewById(R.id.btn_search_system).setOnClickListener(this);
        findViewById(R.id.btn_search_custom).setOnClickListener(this);
        findViewById(R.id.btn_viewpager).setOnClickListener(this);
        findViewById(R.id.btn_radar).setOnClickListener(this);
        findViewById(R.id.btn_sign).setOnClickListener(this);
        findViewById(R.id.btn_pdf).setOnClickListener(this);
        findViewById(R.id.btn_image_point).setOnClickListener(this);
        findViewById(R.id.btn_ftp).setOnClickListener(this);
        findViewById(R.id.btn_recyclerview).setOnClickListener(this);
        findViewById(R.id.btn_swipe_recyclerview).setOnClickListener(this);
        findViewById(R.id.topology).setOnClickListener(this);
        findViewById(R.id.btn_animation).setOnClickListener(this);
        findViewById(R.id.btn_word).setOnClickListener(this);
        findViewById(R.id.btn_dispatch_event).setOnClickListener(this);
        findViewById(R.id.btn_battery).setOnClickListener(this);
        findViewById(R.id.btn_bottom_navigation).setOnClickListener(this);
//        highLightView(findViewById(R.id.btn_alert));
    }

    private void highLightView(View targetView) {
//        PreferencesManager mPreferencesManager = new PreferencesManager(MainActivity.this);
//        mPreferencesManager.resetAll();
//        new SpotlightView.Builder(this)
//                .introAnimationDuration(400)
//                .enableRevealAnimation(true)
//                .performClick(true)
//                .fadeinTextDuration(400)
//                .headingTvColor(Color.RED)
//                .headingTvSize(26)
//                .headingTvText("这是头文字")
//                .subHeadingTvColor(Color.GREEN)
//                .subHeadingTvSize(20)
//                .subHeadingTvText("这是副文字")
//                .maskColor(Color.parseColor("#DC000000")) //背景颜色
//                .target(targetView)
//                .lineAnimDuration(400)
//                .lineAndArcColor(Color.YELLOW)
//                .dismissOnTouch(true)
//                .dismissOnBackPress(true)
//                .enableDismissAfterShown(true)
//                .usageId("target1")
//                .show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_alert:
                alertDialog();
                break;
            case R.id.btn_confirm:
                confirmDialog2();
                break;
            case R.id.btn_add_photo:
                startActivity(new Intent(context, PhotoPreviewActivity.class));
                break;
            case R.id.btn_center_toast:
                ToastUtil.centerToast(this, "居中的Toast");
                break;
            case R.id.btn_pie_chart:
                startActivity(new Intent(context, PieChartActivity.class));
                break;
            case R.id.btn_line_chart:
                startActivity(new Intent(context, LineChartActivity.class));
                break;
            case R.id.btn_grid_view:
                startActivity(new Intent(context, GridRecycleViewActivity.class));
                break;
            case R.id.btn_tips_test:
                showTips();
                break;
            case R.id.btn_to_mine:
                startActivity(new Intent(context, MineActivity.class));
                break;
            case R.id.btn_to_main:
                startActivity(new Intent(context, DrawerLayoutActivity.class));
                break;
            case R.id.btn_bottom_sheet_dialog:
//                showBottomSheetDialog();
//                BottomSheetDialogUtil.init(context, new String[]{"111", "222"}, new OnItemClickListener() {
//                    @Override
//                    public void onItemClick(View view, int i) {
//                        Toast.makeText(context, "点击了" + i + "个", Toast.LENGTH_SHORT).show();
//                    }
//                }).show();
                break;
            case R.id.btn_editview:
                startActivity(new Intent(context, TextInputLayoutActivity.class));
                break;
            case R.id.btn_kotlin:
                startActivity(new Intent(context, KotlinTestActivity.class));
                break;
            case R.id.btn_tablayout:
                startActivity(new Intent(context, TabLayoutActivity.class));
                break;
            case R.id.btn_send_mail:
//                selectFile();
                startActivity(new Intent(context, SendMailActivity.class));
                break;
            case R.id.btn_share:
                showShareDialog();
                break;
            case R.id.btn_db:
                startActivity(new Intent(context, DBActivity.class));
                break;
            case R.id.btn_test:
                startActivity(new Intent(context, TestActivity.class));
                break;
            case R.id.btn_fab:
                startActivity(new Intent(context, FabTestActivity.class));
//                startActivity(new Intent(context, FabAdvanceActivity.class));
                break;
            case R.id.btn_qr:
                startActivity(new Intent(context, QRCodeTestActivity.class));
                break;
            case R.id.btn_map:
                startActivity(new Intent(context, MapActivity.class));
                break;
            case R.id.btn_weather:
                startActivity(new Intent(context, WeatherActivity.class));
                break;
            case R.id.btn_search_system:
                onSearchRequested();
                break;
            case R.id.btn_search_custom:
                startActivity(new Intent(context, Search2Activity.class));
                break;
            case R.id.btn_viewpager:
                startActivity(new Intent(context, ViewPagerActivity.class));
                break;
            case R.id.btn_radar:
                startActivity(new Intent(context, RadarViewActivity.class));
                break;
            case R.id.btn_sign:
                startActivity(new Intent(context, SignActivity.class));
                break;
            case R.id.btn_pdf:
                startActivity(new Intent(context, PDFActivity.class));
                break;
            case R.id.btn_image_point:
                startActivity(new Intent(context, ImagePointActivity.class));
                break;
            case R.id.btn_ftp:
                startActivity(new Intent(context, FTPTestActivity.class));
                break;
            case R.id.btn_recyclerview:
                startActivity(new Intent(context, ScrolledRecylerViewActivity.class));
                break;
            case R.id.btn_swipe_recyclerview:
                startActivity(new Intent(context, SwipeRecyclerViewActivity.class));
                break;
            case R.id.topology:
                startActivity(new Intent(context, TopologyActivity.class));
                break;
            case R.id.btn_animation:
                startActivity(new Intent(context, AnimationActivity.class));
                break;
            case R.id.btn_word:
                Intent intent = new Intent("android.intent.action.VIEW");
                intent.addCategory("android.intent.category.DEFAULT");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/pt_data/file_download/F001LOPT1LHP0010001.docx");
                Uri uri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    uri = FileProvider.getUriForFile(context, getPackageName() + ".provider", file);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    uri = Uri.fromFile(file);
                }
                intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                startActivity(intent);
                break;
            case R.id.btn_dispatch_event:
                startActivity(new Intent(this, DispatchEventActivity.class));
                break;
            case R.id.btn_battery:
                startActivity(new Intent(this, BatteryProgressBarActivity.class));
                break;
            case R.id.btn_bottom_navigation:
                startActivity(new Intent(this, BottomNavigationActivity.class));
                break;
        }
    }

    private void selectFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_FILE);
    }

    private void showBottomSheetDialog() {
        bottomSheetDialog = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.layout_recycleview, null, false);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycle_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        String province = getResources().getString(R.string.c_text_province);
        String[] provinces = province.split(",");
        recyclerView.setAdapter(new TestAdapter(this, provinces));

        bottomSheetDialog.setContentView(view);

        setBehaviorCallback(bottomSheetDialog);
        bottomSheetDialog.show();

    }

    /**
     * 处理bottomSheetDialog打开、关闭后，打不开的问题
     */
    private void setBehaviorCallback(@Nullable final BottomSheetDialog bottomSheetDialog) {
        View view = bottomSheetDialog.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet);
        final BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(view);
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    bottomSheetDialog.dismiss();
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });
    }

    class TestAdapter extends RecyclerView.Adapter<TestAdapter.TestViewHolder> {
        String[] datas;
        LayoutInflater inflater;

        public TestAdapter(Context context, String[] data) {
            this.datas = data;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public TestViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new TestViewHolder(inflater.inflate(R.layout.layout_simple_item, parent, false));
        }

        @Override
        public void onBindViewHolder(TestViewHolder holder, final int position) {
            holder.button.setText(datas[position]);
            holder.button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bottomSheetDialog.dismiss();
                    SnackbarUtil.shortSnackbar(mainView, "选中项: " + "position, 内容是: " + datas[position]);
                }
            });
        }

        @Override
        public int getItemCount() {
            return datas.length;
        }

        class TestViewHolder extends RecyclerView.ViewHolder {

            Button button;

            public TestViewHolder(View itemView) {
                super(itemView);
                button = (Button) itemView.findViewById(R.id.btn_province);
            }
        }
    }

    private int tipType = 1;

    private void showTips() {
        switch (tipType) {
            case 1:
                showPopupWindow(LayoutInflater.from(context).inflate(R.layout.layout_tips, null), findViewById(R.id.btn_tips_test), TOP);
                tipType++;
                break;
            case 2:
                showPopupWindow(LayoutInflater.from(context).inflate(R.layout.layout_tips, null), findViewById(R.id.btn_tips_test), RIGHT);
                tipType++;
                break;
            case 3:
                showPopupWindow(LayoutInflater.from(context).inflate(R.layout.layout_tips, null), findViewById(R.id.btn_tips_test), BOTTOM);
                tipType++;
                break;
            case 4:
                showPopupWindow(LayoutInflater.from(context).inflate(R.layout.layout_tips, null), findViewById(R.id.btn_tips_test), LEFT);
                tipType++;
                break;
            default:
                showPopupWindow(LayoutInflater.from(context).inflate(R.layout.layout_tips, null), findViewById(R.id.btn_tips_test), TOP);
                break;
        }
    }

    /**
     * 使用BottomSheetDialog做分享弹出框
     */
    private void showShareDialog() {
//        MyBottomSheepDialog shareDialog = new MyBottomSheepDialog(context);
//        View view = LayoutInflater.from(context).inflate(R.layout.layout_share_dialog, null);
//        view.findViewById(R.id.share_more).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(Intent.ACTION_SEND);
//                intent.setType("text/*");
//                intent.putExtra(Intent.EXTRA_TEXT, "http://www.baidu.com");
//                startActivity(Intent.createChooser(intent, "分享到"));
//            }
//        });
//        shareDialog.setContentView(view);
//        setBehaviorCallback(shareDialog);
//        shareDialog.show();
    }


    private void alertDialog() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("提示");
        alertDialog.setMessage("这是提示对话框");
        alertDialog.setCancelable(true);
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "点击了确认", Toast.LENGTH_SHORT).show();
                highLightView(findViewById(R.id.btn_line_chart));
                SnackbarUtil.snackbarButton(mainView, "确定退出吗？", "确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
                dialog.cancel();
            }
        });
        alertDialog.show();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));

    }

    private void confirmDialog2() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("这是一个确认提示框")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SnackbarUtil.shortSnackbar(mainView, "点了确认哦");
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SnackbarUtil.longSnackbar(mainView, "lalala");

                    }
                });
        AlertDialog confirmDialog = builder.create();
        confirmDialog.show();
        confirmDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
        confirmDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.color_button_gray));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_FILE && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            ToastUtil.centerToast(context, "选择文件路径：" + uri.toString());
            sendEmail(uri);
        }
    }

    /**
     * 调用设备发送邮件的软件发送邮件
     * @param uri
     */
    private void sendMail(Uri uri) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("application/octet-stream");
        intent.putExtra(Intent.EXTRA_EMAIL, "811792365@qq.com");
        intent.putExtra(Intent.EXTRA_SUBJECT, "hello");
        intent.putExtra(Intent.EXTRA_TEXT, "这是一封来自Android手机的邮件");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(intent, "请选择邮件发送软件"));
    }

    /**
     * 通过JavaMail发送邮件
     * @param uri
     */
    private void sendEmail(Uri uri) {
        final List<String> pathList = new ArrayList<>();
        String path = FileUtils.getPath2(context, uri);
        if (!TextUtils.isEmpty(path)) {
            Log.e("path", path);
            pathList.add(path);
        }
        View view = LayoutInflater.from(context).inflate(R.layout.layout_input, null);
        final TextInputLayout til = (TextInputLayout) view.findViewById(R.id.til_email);
        final EditText et_email = (EditText) view.findViewById(R.id.et_email);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        @SuppressLint("RestrictedApi") final AlertDialog dialog = builder
                .setTitle("提示")
                .setView(view, 20, 10, 20, 10)
                .setNegativeButton("确定", null)
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create();
        dialog.show();

        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = et_email.getText().toString().trim();
                if (!ValidateUtils.isEmail(email)) {
                    til.setError("Invalid email");
                    return;
                } else {
                    SendMailUtils.send("hello", "这是一封来自Android手机的邮件", email, pathList, new SendMailUtils.SendCallBack() {
                        @Override
                        public void sendBack(boolean isSuccess) {
                            if (isSuccess) {
                                SnackbarUtil.shortSnackbar(mainView, "发送成功");
                                dialog.dismiss();
                            } else {
                                SnackbarUtil.shortSnackbar(mainView, "发送失败");
                                dialog.dismiss();
                            }
                        }
                    });
                }
            }
        });

    }


    public void showHighLight() {
//        mHighLight = new HighLight(this)
//                .autoRemove(false)//设置背景点击高亮布局自动移除为false 默认为true
//                .intercept(true)//拦截属性默认为true 使下方ClickCallback生效
//                .enableNext()//开启next模式并通过show方法显示 然后通过调用next()方法切换到下一个提示布局，直到移除自身
//                .anchor(findViewById(R.id.activity_main))//如果是Activity上增加引导层，不需要设置anchor.
//                .addHighLight(R.id.btn_alert, R.layout.info_gravity_left_down, new OnBottomPosCallback(25), new RectLightShape())
//                .addHighLight(R.id.btn_confirm, R.layout.info_gravity_left_down, new OnBottomPosCallback(5), new CircleLightShape())
//                .addHighLight(R.id.btn_add_photo, R.layout.info_gravity_left_down, new OnTopPosCallback(20), new OvalLightShape())
//                .addHighLight(R.id.btn_center_toast, R.layout.info_known, new OnBottomPosCallback(20), new RectLightShape());
//        mHighLight.show();
    }

    public void clickKnown(View view) {
//        if (mHighLight.isShowing() && mHighLight.isNext()) {
//            mHighLight.next();
//        } else {
//            mHighLight.remove();
//        }
    }

    public static final int TOP = 1;
    public static final int BOTTOM = 2;
    public static final int LEFT = 3;
    public static final int RIGHT = 4;

    private PopupWindow popupWindow;

    public void showPopupWindow(View contentView, View anchorView, int mode) {
        contentView.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeWindow(v);
            }
        });
        popupWindow = new PopupWindow(contentView, WRAP_CONTENT, WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setAnimationStyle(R.style.tips_anim);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    popupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        int[] location = new int[2];
        anchorView.getLocationOnScreen(location);
//        popupWindow.showAsDropDown(showAtView, 50, 0);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int windowWidth = contentView.getMeasuredWidth();
        int windowHeight = contentView.getMeasuredHeight();
        int anchorHeight = anchorView.getHeight();
        int anchorWidth = anchorView.getWidth();

        int x = 0, y = 0;
        switch (mode) {
            case TOP:
                x = location[0] + anchorWidth / 2 - windowWidth / 2;
                y = location[1] - windowHeight;
                break;
            case BOTTOM:
                x = location[0] + anchorWidth / 2 - windowWidth / 2;
                y = location[1] + anchorHeight;
                break;
            case LEFT:
                x = location[0] - windowWidth;
                y = location[1] - (windowHeight - anchorHeight) / 2;
                break;
            case RIGHT:
                x = location[0] + anchorWidth;
                y = location[1] - (windowHeight - anchorHeight) / 2;
                break;
        }
        Log.e("location", "x = " + x + ", y = " + y);
        popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY, x, y);
    }

    private void closeWindow(View view) {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

//    private void blurBackground() {
//        Glide.with(this).load(R.mipmap.bg)
//                .bitmapTransform(new BlurTransformation(this, 25), new CenterCrop(this))
//                .into((ImageView) findViewById(R.id.iv_bg));
//    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    private void getUUID() {
        Log.e("MainActivity", DeviceParams.deviceid(this));
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Log.e("MainActivity", tm.getDeviceId());
    }

    public void initScanner() {
        scanner = new ScannerInterface(this);
        /**设置扫描结果的输出模式，参数为0和1：
         * 0为模拟输出，同时广播扫描数据（在光标停留的地方输出扫描结果同时广播扫描数据）;
         * 1为广播输出（只广播扫描数据）；
         * 2为模拟按键输出；
         * */
        scanner.setOutputMode(1);

        IntentFilter intentFilter = new IntentFilter(RES_ACTION);
        ScanResultReceiver receiver = new ScanResultReceiver();
        registerReceiver(receiver, intentFilter);
    }

    private class ScanResultReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (RES_ACTION.equals(intent.getAction())) {
                String scanResult = intent.getStringExtra("value");
                ToastUtil.centerToast(MainActivity.this, scanResult);
            }
        }
    }
}
